package com.joe.demo.chat.protocol;

import com.google.gson.Gson;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @Description 用于扩展序列化、反序列化算法
 * @Author gaojw
 * @Date 2024-09-03
 */
public interface Serializer {

    /**
     * 反序列化
     * @param clazz
     * @param bytes
     * @param <T>
     * @return
     */
    <T> T deserializer(Class<T> clazz, byte[] bytes);

    /**
     * 序列化
     * @param object
     * @param <T>
     * @return
     */
    <T> byte[] serializer(T object);

    /**
     * 序列化 反序列化的算法
     */
    enum Algorithm implements Serializer{
        /**
         * JDK 的序列化和反序列化
         */
        Java {
            @Override
            public <T> T deserializer(Class<T> clazz, byte[] bytes) {
                try {
                    final ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
                    return (T) ois.readObject();
                }catch (IOException | ClassNotFoundException e){
                    throw new RuntimeException("反序列化失败", e);
                }
            }

            @Override
            public <T> byte[] serializer(T object) {
                try {
                    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    final ObjectOutputStream oos = new ObjectOutputStream(bos);
                    oos.writeObject(object);
                    return bos.toByteArray();
                }catch (IOException exception){
                    throw new RuntimeException("序列化失败", exception);
                }
            }
        },

        Json {
            @Override
            public <T> T deserializer(Class<T> clazz, byte[] bytes) {
                final String json = new String(bytes, StandardCharsets.UTF_8);
                return new Gson().fromJson(json, clazz);
            }

            @Override
            public <T> byte[] serializer(T object) {
                final String json = new Gson().toJson(object);
                return json.getBytes(StandardCharsets.UTF_8);
            }
        }
    }
}
